<template>
  <div class="container">
    <el-divider content-position="left">修改密码</el-divider>
    <el-form ref="form" :rules="rules" :model="info" label-width="100px">
      <el-form-item prop="oriPwd" label="旧密码">
        <el-input
          placeholder="请输入旧密码"
          v-model="info.oriPwd"
          show-password
        />
      </el-form-item>
      <el-form-item prop="newPwd" label="新密码">
        <el-input
          placeholder="请输入新密码"
          v-model="info.newPwd"
          show-password
        />
      </el-form-item>
      <el-form-item prop="confirmPwd" label="确认密码">
        <el-input
          placeholder="请再次输入新密码密码"
          v-model="info.confirmPwd"
          show-password
        />
      </el-form-item>
      <div style="text-align: center">
        <el-button @click="submit">
          修改密码
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from "vuex";

export default {
  name: "index",
  data() {
    const confirmPwd = (rule, value, callback) => {
      if (value !== this.info.newPwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const newPwd = (rule, value, callback) => {
      if (value === this.info.oriPwd) {
        callback(new Error("新旧密码不能相同!"));
      } else {
        callback();
      }
    };
    return {
      info: {
        oriPwd: "",
        newPwd: "",
        confirmPwd: ""
      },
      rules: {
        confirmPwd: [
          { validator: confirmPwd, trigger: "blur" },
          { required: true, message: "请再次输入新密码!" }
        ],
        oriPwd: { required: true, message: "请输入当前密码!" },
        newPwd: [
          { validator: newPwd, trigger: "blur" },
          { required: true, message: "请输入新密码!" }
        ]
      }
    };
  },
  methods: {
    ...mapActions(["exitLogin"]),
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.axios.post("/sys/user/updatePwd", this.info).then(res => {
            this.$notify.success("修改密码成功,请重新登录!");
            setTimeout(() => {
              this.exitLogin();
            }, 2000);
          });
        } else return false;
      });
    }
  }
};
</script>

<style scoped>
.el-form {
  width: 400px;
}
</style>
